<template>
  <div id="app">
    <!-- <div>
    <div style="margin: 2px 0">注意：如果有时候按钮不能点击，是因为模型 zIndex 挡住了按钮。</div>
    <div>
      <span>position style：</span>
      <button @click="style = 'position: fixed; top: calc(50% - 250px); left: calc(50% - 200px)'">呆在中间</button>
      <button @click="style = 'position: fixed; top: 0; left: 0; zIndex: 1'">呆在左上角</button>
      <button @click="style = 'position: fixed; top: 0; right: 0; zIndex: 1'">呆在右上角</button>
      <button @click="style = 'position: fixed; bottom: 0; left: 0; zIndex: 1'">呆在左下角</button>
      <button @click="style = 'position: fixed; bottom: 0; right: 0;'">呆在右下角</button>
      <button @click="style = ''">跟随流</button>
    </div>
    <div>
      <span>direction：</span>
      <button @click="direction = 'right'">呆在右边</button>
      <button @click="direction = 'left'">呆在左边</button>
    </div>
    <div>
      <span>size：</span>
      <button @click="size = size - 100; width = width - 100; height = height - 100;">减小</button>
      <button @click="size = size + 100; width = width + 100; height = height + 100;">增大</button>
    </div> -->
    <!-- 可尝试一个页面上多个模型： -->
    <!-- <live2d
      :model="[1, 53]"
      :direction="direction"
      :width="width"
      :height="height"
      customId="vue-live2d-mian-2"
    ></live2d> -->
    <div id="canvas-container">
      <canvas ref="canvas_sakura" id="canvas_sakura" class="bg-sakura"></canvas>
    </div>

    <div
      style="
        width: 300px;
        position: fixed;
        right: 5%;
        bottom: 0;
        z-index: 9999999;
      "
    >
      <live2d
        :style="style"
        :model="['HyperdimensionNeptunia/noir', '00&01&02']"
        :direction="direction"
        :size="size"
      ></live2d>
    </div>

    <!-- </div> -->
    <router-view />
  </div>
</template>
<script>
import live2d from "../src/index.vue";
import { Sakura, SakuraList } from "./components/sakura";
export default {
  name: "App",
  components: {
    live2d,
  },
  computed: {
    background() {
      return this.$store.getters["background/getBackground"];
    },
  },
  methods: {
    // 初始化循环数组
    initParams() {
      for (let index = 0; index < this.sakuraNum; index++) {
        this.limitArray[index] = this.limitTimes;
      }
    },
    initSakura() {
      const img = new Image();
      img.src = "https://p.sda1.dev/12/d4beeab443cd2f2c979763ca780e05d1/sakura.png"; //图片路径使用require才能获取
      //img.src = require("../src/assets/sakura.png"); //图片路径使用require才能获取
      // 绘制樱花
      const _this = this;
      Sakura.prototype.draw = function (cxt) {
        cxt.save();
        const xc = (40 * this.s) / 4;
        cxt.translate(this.x, this.y);
        cxt.rotate(this.r);
        cxt.drawImage(img, 0, 0, 100 * this.s, 100 * this.s); //context.drawImage(img,x,y,width,height);
        cxt.restore();
      };

      // 修改樱花位置,模拟飘落.
      Sakura.prototype.update = function () {
        this.x = this.fn.x(this.x, this.y);
        this.y = this.fn.y(this.y, this.y);
        this.r = this.fn.r(this.r);

        // 如果樱花越界, 重新调整位置
        if (
          this.x > window.innerWidth ||
          this.x < 0 ||
          this.y > window.innerHeight ||
          this.y < 0
        ) {
          // 如果樱花不做限制
          if (_this.limitArray[this.idx] == -1) {
            this.r = _this.getRandom("fnr");
            if (Math.random() > 0.4) {
              this.x = _this.getRandom("x");
              this.y = 0;
              this.s = _this.getRandom("s");
              this.r = _this.getRandom("r");
            } else {
              this.x = window.innerWidth;
              this.y = _this.getRandom("y");
              this.s = _this.getRandom("s");
              this.r = _this.getRandom("r");
            }
          }
          // 否则樱花有限制
          else {
            if (_this.limitArray[this.idx] > 0) {
              this.r = _this.getRandom("fnr");
              if (Math.random() > 0.4) {
                this.x = _this.getRandom("x");
                this.y = 0;
                this.s = _this.getRandom("s");
                this.r = _this.getRandom("r");
              } else {
                this.x = window.innerWidth;
                this.y = _this.getRandom("y");
                this.s = _this.getRandom("s");
                this.r = _this.getRandom("r");
              }
              // 该越界的樱花限制数减一
              _this.limitArray[this.idx]--;
            }
          }
        }
      };
    },
    initSakuraList() {
      SakuraList.prototype.push = function (sakura) {
        this.list.push(sakura);
      };

      // list update 方法
      SakuraList.prototype.update = function () {
        for (let i = 0, len = this.list.length; i < len; i++) {
          this.list[i].update();
        }
      };

      // list draw 方法
      SakuraList.prototype.draw = function (cxt) {
        for (let i = 0, len = this.list.length; i < len; i++) {
          this.list[i].draw(cxt);
        }
      };
      SakuraList.prototype.get = function (i) {
        return this.list[i];
      };
      SakuraList.prototype.size = function () {
        return this.list.length;
      };
    },
    // 位置随机策略
    getRandom(option) {
      let ret, random;
      switch (option) {
        case "x":
          ret = Math.random() * window.innerWidth;
          break;
        case "y":
          ret = Math.random() * window.innerHeight;
          break;
        case "s":
          ret = Math.random();
          break;
        case "r":
          ret = Math.random() * 6;
          break;
        case "fnx":
          random = Math.random() - 0.3;
          ret = function (x, y) {
            return x + 0.5 * random - 1.7;
          };
          break;
        case "fny":
          random = 5 + Math.random() * 0.7;
          ret = function (x, y) {
            return y + random;
          };
          break;
        case "fnr":
          random = Math.random() * 0.03;
          ret = function (r) {
            return r + random;
          };
          break;
      }
      return ret;
    },

    // 樱花入口
    startSakura() {
      const requestAnimationFrame =
        window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;
      const canvas = this.$refs.canvas_sakura;
      canvas.height = window.innerHeight;
      canvas.width = window.innerWidth;
      const cxt = canvas.getContext("2d");
      const sakuraList = new SakuraList();
      // sakuraNum 樱花个数
      for (let i = 0; i < this.sakuraNum; i++) {
        const randomX = this.getRandom("x");
        const randomY = this.getRandom("y");
        const randomR = this.getRandom("r");
        const randomS = this.getRandom("s");
        const randomFnx = this.getRandom("fnx"); //x轴移动速度
        const randomFny = this.getRandom("fny"); //y轴移动速度
        const randomFnR = this.getRandom("fnr"); //转动速度
        const sakura = new Sakura(
          randomX,
          randomY,
          randomS,
          randomR,
          {
            x: randomFnx,
            y: randomFny,
            r: randomFnR,
          },
          i
        );

        sakura.draw(cxt);

        sakuraList.push(sakura);
      }
      let stop = requestAnimationFrame(function f() {
        // console.log("111");
        cxt.clearRect(0, 0, canvas.width, canvas.height);
        // 修改樱花位置逻辑
        sakuraList.update();
        // 画出修改后的樱花
        sakuraList.draw(cxt);
        // 递归 修改位置, 画出修改后的樱花
        stop = requestAnimationFrame(f);
      });
    },
  },
  data() {
    return {
      sakuraNum: 100, //页面樱花数量 (添加)
      limitTimes: -1, //樱花坠落循环次数
      limitArray: [],
      direction: "right",
      style: "",
      width: 500,
      height: 500,
      size: 350,
      tips: {
        mouseover: [
          {
            selector: ".vue-live2d",
            texts: ["这样可以修改默认语句"],
          },
        ],
      },
    };
  },
  created() {
    // tips 未使用，可自行在组件绑定此参数，注意此参数只会初始化一次
    this.tips = this.customTips;
    this.initParams();
    // 获取当前文件夹内的所有图片
    const images = require.context("@/assets", false, /\.(png|jpe?g|gif|webp)$/);

    // 随机选择一张图片作为背景图
    const randomImage =
      images.keys()[Math.floor(Math.random() * images.keys().length)];
    const imageURL = images(randomImage);

    // 将背景图片URL保存到Vuex状态
    this.$store.commit("setBackgroundImageURL", imageURL);

    // 将背景图片设置为背景图
    document.body.style.backgroundImage = `linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(255, 255, 255, 1)), url(${imageURL})`;
  },
  mounted() {
    // 初始化页面参数与对象
    this.initSakura();
    this.initSakuraList();
    // 页面开始坠落樱花
    this.startSakura();
    document.addEventListener("click", this.hidePasswordInput);
    const script = document.createElement("script");
    script.innerHTML = `
      (function() {
        var a_idx = 0;
        window.onclick = function(event) {
          var a = new Array(
            "❤樱岛麻衣❤",
            "❤小鸟游六花❤",
            "❤一花❤",
            "❤二乃❤",
            "❤三玖❤",
            "❤四叶❤",
            "❤五月❤",
            "❤坤坤❤",
            "❤你干嘛❤",
            "❤哎哟❤",
            "❤中分头❤",
            "❤背带裤❤",
            "❤我是❤",
            "❤ikun❤",
            "❤你记住❤",
          );
          var heart = document.createElement("b");
          heart.onselectstart = new Function('event.returnValue=false');
          document.body.appendChild(heart).innerHTML = a[a_idx];
          a_idx = (a_idx + 1) % a.length;
          heart.style.cssText = "position: fixed;left:-100%;";

          var f = 16,
            x = event.clientX - f / 2,
            y = event.clientY - f,
            c = randomColor(),
            a = 1,
            s = 1.2;
          var timer = setInterval(function() {
            if (a <= 0) {
              document.body.removeChild(heart);
              clearInterval(timer);
            } else {
              heart.style.cssText = "font-size:16px;cursor:default;position:fixed;color:" +
                c +
                ";left:" +
                x +
                "px;top:" +
                y +
                "px;opacity:" +
                a +
                ";transform:scale(" +
                s +
                ");";
              y--;
              a -= 0.016;
              s += 0.002;
            }
          }, 15);
        };

        function randomColor() {
          return (
            "rgb(" +
            ~~(Math.random() * 255) +
            "," +
            ~~(Math.random() * 255) +
            "," +
            ~~(Math.random() * 255) +
            ")"
          );
        }
      })();
    `;
    document.body.appendChild(script);
  },
};
</script>
<style>
#canvas-container {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  width: 100vw;
  height: 100%;
}

* {
  margin: 0;
  padding: 0;
}
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

nav {
  padding: 30px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}

body {
  background-image: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0),
      rgba(255, 255, 255, 1)
    ),
    url("../src/assets/2.jpg");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  width: 100%;
  height: 100vh;
  /* 占满全屏 */
  margin: 0;
  padding: 0;
}

.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
}

.input-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
  background-color: white;
  border-radius: 4px;
  z-index: 10000;
}

/* 点击输入框外部区域时隐藏输入框和遮罩层 */
.hide-input {
  display: none;
}
</style>
